<!-- 重构后的任务详情页面 -->
<template>
  <scroll-view 
    scroll-y="true" 
    :refresher-enabled="true"
    :refresher-triggered="refreshing"
    :scroll-into-view="scrollIntoView"
    @refresherrefresh="onRefresh"
    class="scroll-container"
  >
    <!-- 加载状态 -->
    <view v-if="loading" class="loading">
      <text>加载中...</text>
    </view>
    
    <!-- 错误状态 -->
    <view v-else-if="error" class="error">
      <text>{{ error }}</text>
    </view>
    
    <!-- 主要内容 -->
    <view v-else>
      <!-- 任务头部信息 -->
      <TaskHeader 
        :task="taskData"
        @avatar-error="handleTaskAvatarError"
      />
      
      <!-- 任务详情 -->
      <view class="task-body">
        <view class="task-info-row">
          <text class="task-info-label">任务描述:</text>
          <text class="task-info-value">{{ taskData?.description }}</text>
        </view>
        <view class="task-info-row">
          <text class="task-info-label">悬赏金额:</text>
          <text class="task-info-value">{{ formatNumber(taskData?.reward) }} 元</text>
        </view>
        <view class="task-info-row">
          <text class="task-info-label">当前支付:</text>
          <text class="task-info-value">{{ formatNumber(taskData?.currentPaid) }} 元</text>
        </view>
        <view class="task-info-row">
          <text class="task-info-label">任务状态:</text>
          <text class="task-info-value">{{ getStatusText(taskData?.status) }}</text>
        </view>
        <view v-if="taskData?.challengerId && (taskData?.status === '2' || taskData?.status === '3')" class="task-info-row">
          <text class="task-info-label">挑战者:</text>
          <text class="task-info-value">UID {{ formatNumber(taskData?.challengerId) }}</text>
        </view>
      </view>

      <!-- 快捷操作 -->
      <view v-if="showApplyCompleteBtn || isPublisherAndInProgress" class="quick-actions">
        <button v-if="showApplyCompleteBtn" class="apply-shortcut-btn" @click="goToApplyComplete">
          <text>去申请完成</text>
        </button>
        <button v-if="isPublisherAndInProgress" class="apply-shortcut-btn" @click="viewApplyCompleteInfo">
          <text>查看申请完成详情</text>
        </button>
      </view>

      <!-- 任务操作按钮 -->
      <TaskActions
        :show-task-actions="showTaskActions"
        :can-cancel-apply="canCancelApply"
        :can-request-cancel="canRequestCancel"
        :can-delete-task="canDeleteTask"
        :has-pending-messages="hasPendingMessages"
        :pending-message-types="pendingMessageTypes"
        @cancel-apply="handleCancelApply"
        @request-cancel="handleRequestCancel"
        @delete-task="handleDeleteTask"
        @view-messages="goToMessages"
      />

      <!-- 工作记录 -->
      <WorkRecords
        :show-work-controls="taskData?.status === '1' && taskData?.isChallenger"
        :work-loading="workLoading"
        :work-error="workError"
        :work-times="workTimes"
        :is-working="isWorking"
        @start-work="handleStartWork"
        @end-work="handleEndWork"
      />

      <!-- 团队管理 -->
      <TeamManagement
        :task-id="taskId"
        :team-info="teamInfo"
        :is-team-leader="isTeamLeader"
        :show-team-section="teamMode && taskData?.status === '1'"
        @open-invitation="handleOpenInvitation"
        @dissolve-team="handleDissolveTeam"
        @leave-team="handleLeaveTeam"
        @create-team="handleCreateTeam"
        @invite-success="handleInviteSuccess"
      />

      <!-- 投票系统 -->
      <VoteSystem
        :show-vote-section="teamMode && taskData?.status === '2'"
        :active-vote="activeVote"
        :vote-history="voteHistory"
        :can-initiate-vote="teamInfo && teamInfo.memberCount > 1"
        :is-team-leader="isTeamLeader"
        :has-voted="hasVoted"
        :user-vote="userVote"
        @vote="handleVote"
        @initiate-remove-vote="handleInitiateRemoveVote"
        @initiate-impeach-vote="handleInitiateImpeachVote"
      />

      <!-- 待处理消息提示 -->
      <view v-if="hasPendingMessages" class="pending-messages">
        <text class="pending-title">有待处理的消息</text>
        <view v-for="msgType in pendingMessageTypes" :key="msgType" class="pending-item">
          <text v-if="msgType === 3">• 任务申请待处理</text>
          <text v-else-if="msgType === 9">• 取消申请待处理</text>
          <text v-else-if="msgType === 4">• 完成申请待处理</text>
        </view>
        <button class="view-messages-btn" @click="goToMessages">
          <text>查看消息</text>
        </button>
      </view>
    </view>
  </scroll-view>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { onLoad, onShow } from '@dcloudio/uni-app'

// 导入组件
import TaskHeader from './components/TaskHeader.vue'
import TaskActions from './components/TaskActions.vue'
import TeamManagement from './components/TeamManagement.vue'
import VoteSystem from './components/VoteSystem.vue'
import WorkRecords from './components/WorkRecords.vue'

// 导入 Composables
import { useTaskData } from './composables/useTaskData.js'
import { useTeamManagement } from './composables/useTeamManagement.js'
import { useVoteSystem } from './composables/useVoteSystem.js'
import { useWorkRecords } from './composables/useWorkRecords.js'
import { useWebSocket } from './composables/useWebSocket.js'

// 页面参数
const taskId = ref(null)

// 使用 Composables
const {
  taskData,
  loading,
  error,
  refreshing,
  showTaskActions,
  canCancelApply,
  canRequestCancel,
  canDeleteTask,
  isPublisherAndInProgress,
  showApplyCompleteBtn,
  fetchTaskDetail,
  refreshTaskData,
  formatNumber,
  getStatusText,
  getAvatarUrl
} = useTaskData()

const {
  teamInfo,
  isTeamLeader,
  teamMode,
  showTeamInvitationModal,
  teamLoading,
  teamError,
  showTeamSection,
  checkExistingTeam,
  createTeam,
  leaveTeam,
  dissolveTeam,
  openInvitationModal,
  closeInvitationModal
} = useTeamManagement()

const {
  activeVote,
  voteHistory,
  hasVoted,
  userVote,
  voteLoading,
  voteError,
  showVoteSection,
  canInitiateVote,
  fetchActiveVote,
  fetchVoteHistory,
  submitVote,
  initiateRemoveVote,
  initiateImpeachVote
} = useVoteSystem()

const {
  workTimes,
  workLoading,
  workError,
  isWorking,
  currentWorkStart,
  showWorkControls,
  totalWorkTime,
  fetchWorkTimes,
  startWork,
  endWork,
  formatDateTime,
  calculateDuration,
  formatWorkTime
} = useWorkRecords()

const {
  wsConnected,
  wsRetryCount,
  connectWebSocket,
  disconnect,
  sendMessage,
  handleWebSocketMessage
} = useWebSocket()

// 其他响应式数据
const scrollIntoView = ref('')
const hasPendingMessages = ref(false)
const pendingMessageTypes = ref([])

// 页面加载
onLoad((options) => {
  if (options.taskId) {
    taskId.value = options.taskId
    loadPageData()
  }
})

// 页面显示
onShow(() => {
  if (taskId.value) {
    refreshPageData()
  }
})

// 加载页面数据
const loadPageData = async () => {
  if (!taskId.value) return
  
  try {
    // 并行加载所有数据
    await Promise.all([
      fetchTaskDetail(taskId.value),
      checkExistingTeam(taskId.value),
      fetchWorkTimes(taskId.value)
    ])
    
    // 如果团队存在，加载投票信息
    if (teamInfo.value) {
      await Promise.all([
        fetchActiveVote(teamInfo.value.teamId),
        fetchVoteHistory(teamInfo.value.teamId)
      ])
    }
    
    // 检查待处理消息
    await checkPendingMessages()
  } catch (err) {
    console.error('加载页面数据失败:', err)
  }
}

// 刷新页面数据
const refreshPageData = async () => {
  if (!taskId.value) return
  
  try {
    await refreshTaskData()
    await checkExistingTeam(taskId.value)
    await fetchWorkTimes(taskId.value)
    
    if (teamInfo.value) {
      await fetchActiveVote(teamInfo.value.teamId)
    }
    
    await checkPendingMessages()
  } catch (err) {
    console.error('刷新页面数据失败:', err)
  }
}

// 下拉刷新
const onRefresh = async () => {
  await refreshPageData()
}

// 检查待处理消息
const checkPendingMessages = async () => {
  try {
    const token = uni.getStorageSync('accessToken')
    if (!token) return

    const response = await uni.request({
      url: '${NETWORK_CONFIG.API_BASE_URL}/message/pending',
      method: 'GET',
      header: {
        'Access-Token': `Bearer ${token}`
      }
    })

    if (response.data && response.data.success) {
      const messages = response.data.data || []
      hasPendingMessages.value = messages.length > 0
      pendingMessageTypes.value = [...new Set(messages.map(msg => msg.type))]
    }
  } catch (err) {
    console.error('检查待处理消息失败:', err)
  }
}

// 事件处理
const handleTaskAvatarError = () => {
  console.log('任务头像加载失败')
}

const handleCancelApply = async () => {
  // 实现撤回申请逻辑
  console.log('撤回申请')
}

const handleRequestCancel = () => {
  // 实现申请取消任务逻辑
  console.log('申请取消任务')
}

const handleDeleteTask = async () => {
  // 实现删除任务逻辑
  console.log('删除任务')
}

const handleStartWork = async () => {
  if (taskId.value) {
    await startWork(taskId.value)
  }
}

const handleEndWork = async () => {
  if (taskId.value) {
    await endWork(taskId.value)
  }
}

const handleOpenInvitation = () => {
  openInvitationModal()
}

const handleDissolveTeam = async () => {
  if (teamInfo.value?.teamId) {
    const confirmed = await new Promise((resolve) => {
      uni.showModal({
        title: '解散团队',
        content: '确定要解散当前团队吗？',
        success: (res) => resolve(res.confirm)
      })
    })
    
    if (confirmed) {
      await dissolveTeam(teamInfo.value.teamId)
    }
  }
}

const handleLeaveTeam = async () => {
  if (teamInfo.value?.teamId) {
    const confirmed = await new Promise((resolve) => {
      uni.showModal({
        title: '退出团队',
        content: '确定要退出当前团队吗？',
        success: (res) => resolve(res.confirm)
      })
    })
    
    if (confirmed) {
      await leaveTeam(teamInfo.value.teamId)
    }
  }
}

const handleCreateTeam = async () => {
  if (taskId.value) {
    await createTeam(taskId.value)
  }
}

const handleInviteSuccess = () => {
  // 刷新团队信息
  if (taskId.value) {
    checkExistingTeam(taskId.value)
  }
}

const handleVote = async (voteData) => {
  if (activeVote.value?.id) {
    await submitVote(activeVote.value.id, voteData.approve)
  }
}

const handleInitiateRemoveVote = () => {
  // 实现发起踢人投票逻辑
  console.log('发起踢人投票')
}

const handleInitiateImpeachVote = () => {
  // 实现发起弹劾投票逻辑
  console.log('发起弹劾投票')
}

const goToApplyComplete = () => {
  uni.navigateTo({
    url: '/pages/task/work-verify/index'
  })
}

const viewApplyCompleteInfo = () => {
  // 实现查看申请完成详情逻辑
  console.log('查看申请完成详情')
}

const goToMessages = () => {
  uni.navigateTo({
    url: '/pages/message/index'
  })
}

// 监听团队信息变化
watch(teamInfo, (newTeamInfo) => {
  if (newTeamInfo?.teamId) {
    fetchActiveVote(newTeamInfo.teamId)
    fetchVoteHistory(newTeamInfo.teamId)
  }
})

// 监听WebSocket消息
uni.$on('team-update', (message) => {
  console.log('收到团队更新消息:', message)
  if (taskId.value) {
    checkExistingTeam(taskId.value)
  }
})

uni.$on('vote-update', (message) => {
  console.log('收到投票更新消息:', message)
  if (teamInfo.value?.teamId) {
    fetchActiveVote(teamInfo.value.teamId)
  }
})

uni.$on('task-progress-update', (message) => {
  console.log('收到任务进度更新:', message)
  if (taskId.value) {
    refreshTaskData()
  }
})
</script>

<style scoped>
.scroll-container {
  height: 100vh;
  background: #f5f5f5;
}

.loading,
.error {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 200rpx;
  font-size: 28rpx;
}

.loading {
  color: #666;
}

.error {
  color: #f44336;
}

.task-body {
  background: #fff;
  margin: 20rpx;
  padding: 20rpx;
  border-radius: 16rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
}

.task-info-row {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 20rpx;
  padding-bottom: 20rpx;
  border-bottom: 1rpx solid #f0f0f0;
}

.task-info-row:last-child {
  border-bottom: none;
  margin-bottom: 0;
}

.task-info-label {
  font-size: 28rpx;
  color: #666;
  font-weight: 500;
  min-width: 160rpx;
}

.task-info-value {
  font-size: 28rpx;
  color: #333;
  flex: 1;
  text-align: right;
  line-height: 1.4;
}

.quick-actions {
  margin: 20rpx;
  display: flex;
  gap: 20rpx;
}

.apply-shortcut-btn {
  flex: 1;
  padding: 20rpx;
  background: #4CAF50;
  color: white;
  border-radius: 12rpx;
  font-size: 28rpx;
  font-weight: 500;
  border: none;
}

.pending-messages {
  margin: 20rpx;
  padding: 20rpx;
  background: #fff3cd;
  border: 2rpx solid #ffeaa7;
  border-radius: 12rpx;
}

.pending-title {
  font-size: 28rpx;
  font-weight: bold;
  color: #856404;
  margin-bottom: 10rpx;
  display: block;
}

.pending-item {
  font-size: 26rpx;
  color: #856404;
  margin-bottom: 8rpx;
}

.view-messages-btn {
  background: #ffc107;
  color: #333;
  padding: 16rpx 32rpx;
  border-radius: 8rpx;
  font-size: 26rpx;
  font-weight: 500;
  border: none;
  margin-top: 10rpx;
}
</style>
